# -*- coding: utf-8 -*-

from service import Service
import time

directions = {
	"Stop":			0,
	"Forward": 		1,
	"Backward": 	2,
	"Left": 		3,
	"Right": 		4,
	"RotateLeft": 	5,
	"RotateRight": 	6,
	"ForwardLeft": 	7,
	"ForwardRight":	8,
	"BackwardLeft":	9,
	"BackwardRight":10,
	"HeadUp":		11,
	"HeadDown": 	12,
	"HeadMiddle": 	13,
	"Reserved1":	14,
	"Reserved2":	15,
	"Reserved3":	16,
	"RotateLeft20":	17,
	"RotateRight20":18,
	}

class Driver(Service):
	""" Provides a service that exposes drive* functions
		which can be called with an optional speed parameter
		and an optional length of time parameter
	"""
	cmd = "nav"
	script = "rev"

	def __init__(self, robot, speed=5):
		""" Speed is a value from 1 to 10 (inclusive) that
			defines how fast to move the rovio by default
			1 is fastest, 10 is slowest
		"""

		Service.__init__(self, robot)
		
		self.speed = speed

	def _drive(self, direction, speed=0, t=0):
		""" Not directly called, this is used to generate the drive* functions
			if speed is 0 then the default is used,
			if t > 0 then the robot moves the desired way for that length of time
			in seconds
		"""
		if not speed:
			speed = self.speed

		if not t:
			return self._sendCommand({"drive":directions[direction], "action":18, "speed":speed})
		else:
			while t > 0:
				start = time.time()
				self._sendCommand({"drive":directions[direction], "action":18, "speed":speed})
				t -= time.time() - start


	def __getattr__(self, name):
		""" Returns what you're looking for unless that
			happens to start with drive, then it returns the correct
			drive function.
		"""
		if name.find("drive") == 0 and name[5:]:
			def f(speed=0, time=0):
				return self._drive(name[5:], speed, time)
			return f

	